package dao;

import java.sql.*;
import java.util.LinkedList;

public class ConnectionManager {

	private static String driver = "org.hsqldb.jdbcDriver";
	private static String url = "jdbc:hsqldb:hsql://localhost/Library";
	private static String user = "sa";
	private static String password = "";
	private static ConnectionManager manager;
	private static final int STEP = 5;
	private LinkedList<Connection> connections;

	private ConnectionManager() {
		connections = new LinkedList<Connection>();
	}

	public static ConnectionManager getInstance() {
		if (manager == null) {
			manager = new ConnectionManager();
		}
		return manager;
	}

	private synchronized void addConnections() {
		for (int i = 0; i < STEP; i++) {
			try {
				Class.forName(driver);
				Connection conn = DriverManager.getConnection(url, user,
						password);
				connections.add(conn);
			} catch (Exception e) {
				System.out.println("Connection cannot be added");
				e.printStackTrace();
			}
		}
	}

	public synchronized Connection getConnection() {
		if (connections.isEmpty()) {
			addConnections();
		}
		return connections.remove();
	}

	public synchronized void returnConnection(Connection conn) {
		if (connections.size() < STEP) {
			connections.add(conn);
		} else {
			try {
				conn.close();
			} catch (Exception e) {
			}
		}
	}
}